
import csv
import os

from config import DATABASE_FIELDNAMES, REFERRAL_DATABASE_FILE_PATH
from log import logger


def validate_data(data, item=''):
    write_data = {}
    for i in data:
        j = item + i
        if isinstance(data[i], str):
            write_data[j] = data[i]
        elif isinstance(data[i], bool):
            write_data[j] = str(data[i])
        elif isinstance(data[i], dict):
            k = validate_data(data[i], item=j+'_')
            for b in k: write_data[b] = k[b]
        else:
            logger.error(f'code: 38aSUwmk; {type(d)}')
    return write_data


def create_db(_file=REFERRAL_DATABASE_FILE_PATH):
    with open(_file, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(DATABASE_FIELDNAMES)

def create_row(data, _file=REFERRAL_DATABASE_FILE_PATH):

    data = validate_data(data)
    write_data = [ str(data[fieldname]) for fieldname in DATABASE_FIELDNAMES]

    with open(_file, 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(write_data)
    return {
        'row': data
    }

def read_all(_file=REFERRAL_DATABASE_FILE_PATH):
    with open(_file, 'r', newline='') as f:
        reader = csv.reader(f)
        data = [ i for i in reader ]
    return {
        'rows': data
    }

def read(column, row, _file=REFERRAL_DATABASE_FILE_PATH):
    with open(_file, 'r', newline='') as f:
        reader = csv.reader(f)
        data = [ dict(zip(DATABASE_FIELDNAMES, i)) for i in reader ]
    return data[row][column]

def update(_file=REFERRAL_DATABASE_FILE_PATH):
    pass

def delete(_file=REFERRAL_DATABASE_FILE_PATH):
    pass

def init(_file=REFERRAL_DATABASE_FILE_PATH):
    if os.path.exists(_file):
        data = read_all(_file)
        if not data['rows']:
            create_db(_file)
            logger.info(f'create new database: {_file}')
    else:
        create_db(_file)
